/**
 * API密钥验证器
 * 用于实际验证LLM提供商API密钥的有效性
 */

const https = require('https');
const http = require('http');

class ApiValidator {
    constructor() {
        this.requestTimeout = 10000; // 10秒超时
    }

    /**
     * 验证提供商API密钥
     * @param {string} providerName - 提供商名称
     * @param {string} baseUrl - API基础URL
     * @param {string} apiKey - API密钥
     * @returns {Promise<Object>} 验证结果
     */
    async validateProvider(providerName, baseUrl, apiKey) {
        try {
            const models = await this.fetchProviderModels(baseUrl, apiKey);

            if (models && models.length > 0) {
                return {
                    success: true,
                    provider: providerName,
                    models: models,
                    modelCount: models.length,
                    message: `${providerName} API密钥验证成功，获取到${models.length}个模型`
                };
            } else {
                return {
                    success: false,
                    provider: providerName,
                    error: '无法获取模型列表，请检查API密钥是否正确'
                };
            }
        } catch (error) {
            return {
                success: false,
                provider: providerName,
                error: `API验证失败: ${error.message}`
            };
        }
    }

    /**
     * 获取提供商的模型列表
     * @param {string} baseUrl - API基础URL
     * @param {string} apiKey - API密钥
     * @returns {Promise<Array>} 模型列表
     */
    async fetchProviderModels(baseUrl, apiKey) {
        return new Promise((resolve, reject) => {
            const url = `${baseUrl}/models`;
            const options = {
                headers: {
                    'Authorization': `Bearer ${apiKey}`,
                    'Content-Type': 'application/json'
                },
                timeout: this.requestTimeout
            };

            const client = url.startsWith('https://') ? https : http;
            const req = client.request(url, options, (res) => {
                let body = '';
                res.on('data', chunk => body += chunk);
                res.on('end', () => {
                    try {
                        if (res.statusCode === 200) {
                            const data = JSON.parse(body);
                            // 过滤出支持视觉的模型
                            const visionModels = data.data?.filter(model =>
                                model.id && (
                                    model.id.includes('vision') ||
                                    model.id.includes('image') ||
                                    model.id.includes('multimodal') ||
                                    model.id.includes('4v') || // 智谱的4v模型
                                    model.id.includes('gpt-4-vision') || // OpenAI的视觉模型
                                    model.id.includes('claude-3-vision') // Anthropic的视觉模型
                                )
                            ) || [];

                            // 如果有视觉模型就返回视觉模型，否则返回所有模型
                            resolve(visionModels.length > 0 ? visionModels : data.data || []);
                        } else {
                            reject(new Error(`HTTP ${res.statusCode}: ${body.substring(0, 200)}`));
                        }
                    } catch (e) {
                        reject(new Error(`解析响应失败: ${e.message}`));
                    }
                });
            });

            req.on('error', (error) => {
                reject(new Error(`网络请求失败: ${error.message}`));
            });

            req.on('timeout', () => {
                req.destroy();
                reject(new Error('请求超时，请检查网络连接'));
            });

            req.setTimeout(this.requestTimeout);
            req.end();
        });
    }

    /**
     * 批量验证多个提供商
     * @param {Array} providers - 提供商配置数组
     * @returns {Promise<Array>} 验证结果数组
     */
    async validateMultipleProviders(providers) {
        const results = [];

        for (const provider of providers) {
            console.log(`正在验证 ${provider.name} 提供商...`);
            const result = await this.validateProvider(provider.name, provider.baseUrl, provider.apiKey);
            results.push(result);

            // 添加延迟避免请求过快
            if (results.length < providers.length) {
                await new Promise(resolve => setTimeout(resolve, 500));
            }
        }

        return results;
    }

    /**
     * 验证单个提供商并返回详细信息
     * @param {Object} config - 提供商配置对象
     * @returns {Promise<Object>} 详细验证结果
     */
    async validateProviderDetailed(config) {
        const startTime = Date.now();
        const result = await this.validateProvider(config.name, config.baseUrl, config.apiKey);
        const endTime = Date.now();

        return {
            ...result,
            responseTime: endTime - startTime,
            timestamp: new Date().toISOString()
        };
    }
}

module.exports = ApiValidator;